var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;

function gulpGlobalVar(obj) {

  var strs = []
  Object.keys(obj).forEach(key => {
    var str
    var value = obj[key]
    var type = Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
    switch (type) {
      case 'string':
        str = `${key}=${value};`
        break;
      case 'object':
        str = `${key}=${JSON.stringify(value)};`
        break
    }
    strs.push(str)
  });

  var str = strs.join('')

  str = new Buffer(str); // 提前分配
  // 创建一个让每个文件通过的 stream 通道
  var stream = through.obj(function (file, enc, cb) {
    if (file.isBuffer()) {
      file.contents = Buffer.concat([str, file.contents]);
      // this.emit('error', new PluginError(PLUGIN_NAME, 'Buffers not supported!'));
    }
    // 确保文件进去下一个插件
    this.push(file);
    // 告诉 stream 转换工作完成
    cb();
  });
  // 返回文件 stream
  return stream;
}

module.exports = gulpGlobalVar;